const express = require("express");
const bodyParser = require('body-parser');
const expressIp = require("express-ip");
const { FastAPIPortCreateErrorException, FastAPIUknowPortException, FastAPIPortRangeException, FastAPIException } = require("./FastAPIException");



class FastAPIPortPool{
    constructor(){
        this.pool = {};
    }

    static createPort(port,success = function(){}){
        let api = express();
        api.use(bodyParser.json());
        api.use(bodyParser.json());
        api.use(bodyParser.urlencoded({ extended: false }));
        api.use(expressIp().getIpInfoMiddleware);//IP信息中间件
        
        try{
            api.listen(port,success);
        }catch(e){
            throw new FastAPIPortCreateErrorException();
        }
        return api;
    }

    hasPort(port){
        if(this.pool[port] == undefined){
            return false;
        }

        return true;
    }

    getPort(port){
        if(this.hasPort(port)){
            let _r = this.pool[port];
            if(_r instanceof Express){
                return _r;
            }
        }

        let target = FastAPIPortPool.createPort(port);
        if(target){
            this.pool[port] = target;
        }
        return target;
    }
}


let fastApiPortPool = new FastAPIPortPool();


class API{
    constructor(config = {}){
        let {
            path,
            port = -1,
            method,
        } = config;

        this.path = path;
        this.port = port;
        this.method = method;
    }

    setPath(path){
        this.path = path;
    }

    setPort(port){
        this.port = port;
    }

    setMethod(method){
        this.method = method;
    }

    //ToOverride
    onRequest(data,res,req){

    }


    start(method = "GET"){
        method = method || this.method;
        //判断端口是否有效
        let targetPort = new Number(this.port).valueOf();
        if(isNaN(targetPort)){
            throw new FastAPIUknowPortException(this.port);
        }

        if(targetPort < 1 || targetPort > 65535){
            throw new FastAPIPortRangeException(this.port);
        }

        let port = fastApiPortPool.getPort(targetPort);

        //检查路径
        if(this.path == undefined || this.path == ""){
            throw new FastAPIException(`错误的路径：${this.path}`);
        }

        //onRequest(data,res,req)
        if(method == "GET"){
            port.get(this.path,(req,res) => {
                this.onRequest(req.query,res,req);
            })
        }else if(method == "POST"){
            port.post(this.path,(req,res) => {
                this.onRequest(req.body,res,req);
            })
        }
    }
}

class Server{

    constructor(){
        this.apis = [];
    }

    addAPI(api){
        if(api instanceof API){
            this.apis.push(api);
        }else{
            console.warn(`${api.constructor.name} 不是一个有效的 API 实例`);
        }
    }

    start(port){
        for(let api of this.apis){
            try{
                api.setPort(port);
                api.start();
                console.log(`${api.constructor.name} 已启动在 :${api.port}${api.path}`);
            }catch(e){
                console.warn(e);
            }
        }
    }
}



module.exports.API = API;
module.exports.Server = Server;
module.exports.POST = "POST";
module.exports.GET = "GET";

